package com.thysdy.flowable.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

public class TransferUtil {
    /**
     * bean转为另一个bean
     * @param source
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T>T transfer(Object source,Class<T> targetClass){
        if (source == null){
            return null;
        }
        try {
            T t = targetClass.newInstance();
            BeanUtils.copyProperties(source,t);
            return t;
        } catch (InstantiationException e) {
            // e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            // e.printStackTrace();
            return null;
        }
    }

    /**
     * 泛型为一种bean的list转为另一种泛型bean的list
     * @param sourceList 原list
     * @param targetClass 替换bean
     * @return
     */
	public static <T> List<T> transferList(List<?> sourceList, Class<T> targetClass) {
        List<T> result = null;
        if (!CollectionUtils.isEmpty(sourceList)) {
            result = sourceList.stream().map((source) -> transfer(source, targetClass))
                    .collect(Collectors.toList());
        }
        return result;
	}
}
